import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

interface InitialStateType {
  projects: Bn.Meta.MetaProject[];
  currentProject: Bn.Meta.MetaProject | null;
}

const initialState: InitialStateType = {
  projects: [] as Bn.Meta.MetaProject[],
  currentProject: null
};

export const cfgSlice = createSlice({
  name: 'config',
  initialState,
  reducers: {
    setProjects(state, { payload }: PayloadAction<Bn.Meta.MetaProject[]>) {
      console.debug('prjSlice::setProjects', payload);
      state.projects = payload;
      if (state.projects.length > 0) {
        state.currentProject = state.projects[0];
      }
    },
    changeProject(state, { payload }: PayloadAction<Bn.Meta.MetaProject>) {
      console.debug('prjSlice::changeProject', payload);
      state.currentProject = payload;
    }
  },
  selectors: {
    getProjects: state => state.projects,
    getProject: state => state.currentProject
  }
});

export const { setProjects, changeProject } = cfgSlice.actions;
export const { getProjects, getProject } = cfgSlice.selectors;
